package com.pclong.fightlandlordserver.command.handler;

import com.pclong.fightlandlordserver.command.handler.PlatformInMessageHandler;
import com.pclong.fightlandlordserver.command.message.EchoMessage;
import com.pclong.fightlandlordserver.command.message.F3ServerMessage;
import com.pclong.fightlandlordserver.command.message.PlatformMessage;
import com.pclong.fightlandlordserver.command.message.F3ServerMessage.MessageType;
import com.pclong.fightlandlordserver.command.message.game.FightLandlordGameMessage;
import com.pclong.fightlandlordserver.data.HibernateSessionFactory;
import com.pclong.fightlandlordserver.data.HibernateTransactionSupport;
import com.pclong.fightlandlordserver.data.metadata.PlayerProfile;
import com.pclong.fightlandlordserver.data.metadata.PlayerProfileDAO;
import com.pclong.fightlandlordserver.game.GamePool;
import com.pclong.fightlandlordserver.game.model.FightLandlordGame;
import com.pclong.fightlandlordserver.game.model.FightLandlordGameSetting;
import com.pclong.fightlandlordserver.game.model.FightLandlordPoker;
import com.pclong.fightlandlordserver.game.model.GameStatus;
import com.pclong.fightlandlordserver.game.model.Player;
import com.pclong.fightlandlordserver.game.model.Room;
import com.pclong.fightlandlordserver.model.PlayerResult;
import com.pclong.fightlandlordserver.model.RoomResult;
import com.pclong.fightlandlordserver.util.ConvertUtil;
import com.pclong.fightlandlordserver.util.ModelUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

//import com.sun.xml.internal.ws.api.pipe.Tube;
import com.pclong.fightlandlordserver.game.Game;
import com.pclong.fightlandlordserver.util.DateUtil;
import com.pclong.fightlandlordserver.util.EncryptionUtil;
import com.pclong.fightlandlordserver.util.HandlerDispatcher;
import com.pclong.fightlandlordserver.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.mina.core.session.IoSession;

/**
 * 斗地主消息控制句柄
 */
public class FightLandlordGameInMessageHandler extends GameInMessageHandler<FightLandlordGameMessage> {

    public static final String GAME_SETTING_UPDATE_FINISH = "GAME_SETTING_UPDATE_FINISH";
    public static final String GAME_BOMB = "GAME_BOMB";
    protected Gson gson = new GsonBuilder().setPrettyPrinting().create();

    @Override
    public void GAME_JOIN_MATCHING_QUEUE(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        // 判断当前玩家是否有足够分数加入游戏
        Player currentPlayer = ModelUtil.getPlayer(session);

        if (!GameStatus.IDLE.equals(currentPlayer.getCurrentStatus())) {
            // 游戏状态判断
            return;
        }

        Room currentRoom = currentPlayer.getCurrentRoom();
        HibernateSessionFactory.getSession().clear();
        PlayerProfile currentPlayerProfile = new PlayerProfileDAO().findByUserId(currentPlayer.getId()).get(0);
        if (currentPlayerProfile.getCurrentScore() < currentRoom.getMinGameMarks()) {
            currentPlayer.setCurrentStatus(GameStatus.IDLE);
            String content = "当前房间所需最低游戏分数为" + currentPlayer.getCurrentRoom().getMinGameMarks() + "分，您的分数不足，请充值！";
            echoMessage.setResult(GAME_WAIT);
            echoMessage.setContent(content);
            sessionWrite(session, echoMessage);
            return;
        }

        // 将当前玩家加入游戏等待队列中
        ModelUtil.getPlayer(session).setCurrentStatus(GameStatus.MATCHING);

        // 判断当前房间内等候的玩家个数是否足够以开始游戏
        int groupQuantity = new Integer(ModelUtil.getSystemParameter("WAITING_QUEUE_GROUP_QUANTITY"));

        if (currentRoom.getGameStatusNumber(GameStatus.MATCHING) < FightLandlordGame.PLAYER_COGAME_NUMBER * groupQuantity) {
            int numPlayers = currentRoom.getGameStatusNumber(GameStatus.MATCHING);
            numPlayers += Math.ceil(numPlayers / (FightLandlordGame.PLAYER_COGAME_NUMBER - 1));
            int matchingRate = (int) Math.round((double) numPlayers / (FightLandlordGame.PLAYER_COGAME_NUMBER * groupQuantity) * 100);
            if (matchingRate == 100) {
                matchingRate = (int) Math.round(((double) numPlayers - new Integer(ModelUtil.getSystemParameter("WAITING_QUEUE_GROUP_QUANTITY")))
                        / (FightLandlordGame.PLAYER_COGAME_NUMBER * groupQuantity) * 100);
            }
            String content = "当前房间等候的玩家数不足以开始新的游戏，系统配对比率为【" + matchingRate + "%】，请稍候。";
            echoMessage.setResult(GAME_WAIT);
            echoMessage.setContent(content);
            Set<IoSession> sessions = ModelUtil.getSessions();
            synchronized (sessions) {
                Iterator<IoSession> itr = sessions.iterator();
                while (itr.hasNext()) {
                    // 向同房间内的玩家发生消息
                    session = itr.next();
                    currentPlayer = ModelUtil.getPlayer(session);
                    if (currentPlayer != null && GameStatus.MATCHING.equals(currentPlayer.getCurrentStatus())) {
                        sessionWrite(session, echoMessage);
                    }
                }
            }
            return;
        }

        // 开始游戏
        GAME_START(session, message, echoMessage);
    }

    @Override
    public synchronized void GAME_START(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        // 取得玩家所在房间内所有的玩家
        Map<String, Player> playersInRoom = ModelUtil.getPlayer(session).getCurrentRoom().getChildren();
        synchronized (playersInRoom) {
            // 取得当前房间内的等待队列中的玩家
            List<Player> playersInQueue = new ArrayList<Player>();
            Set<String> tempPool4IP = new HashSet<String>();
            // FIXME This line should rewrite when IP excluded parameter is added!
            boolean sameIPexcluded = ModelUtil.getSystemParameter("") != null ? Boolean.getBoolean(ModelUtil.getSystemParameter("").toLowerCase()) : false;
            for (Player eachPlayer : playersInRoom.values()) {
                if (sameIPexcluded && tempPool4IP.contains(eachPlayer.getIosession().getRemoteAddress().toString())) {
                    // 过滤IP相同的玩家
                    continue;
                } else if (sameIPexcluded) {
                    tempPool4IP.add(eachPlayer.getIosession().getRemoteAddress().toString());
                }
                if (GameStatus.MATCHING.equals(eachPlayer.getCurrentStatus())) {
                    playersInQueue.add(eachPlayer);
                }
            }
            // 按照等候的优先顺序进行排序，使先进入等待队列的玩家排在前面
            Collections.sort(playersInQueue, new Comparator<Player>() {

                public int compare(Player p1, Player p2) {
                    if (p1.getLastPlayTime() < p2.getLastPlayTime()) {
                        return 1;
                    } else if (p1.getLastPlayTime() > p2.getLastPlayTime()) {
                        return -1;
                    }
                    return 0;
                }
            });
            // 按照系统设置的最大游戏开始人数进行人数截取
            int groupQuantity = new Integer(ModelUtil.getSystemParameter("WAITING_QUEUE_GROUP_QUANTITY"));
            if (playersInQueue.size() < FightLandlordGame.PLAYER_COGAME_NUMBER * groupQuantity) {
                groupQuantity = playersInQueue.size() / FightLandlordGame.PLAYER_COGAME_NUMBER;
                if (groupQuantity == 0) {
                    return;
                }
            }
            playersInQueue = playersInQueue.subList(0, FightLandlordGame.PLAYER_COGAME_NUMBER * groupQuantity);


            if ("true".equals(ModelUtil.getSystemParameter("WAITING_QUEUE_RANDOM_ENABLE").toLowerCase())) {
                // 将玩家再次随机调整顺序
                Collections.shuffle(playersInQueue);
            }
            List<Player> playersInGroup = new ArrayList<Player>();
            for (int i = 0; i < playersInQueue.size(); i++) {
                playersInGroup.add(playersInQueue.get(i));
                if ((i + 1) % FightLandlordGame.PLAYER_COGAME_NUMBER != 0) {
                    continue;
                }
                // 根据玩家当前的所在的房间进来开始游戏
                String gameId = GamePool.prepareFightLandlordGame(playersInGroup);
                for (Player eachPlayer : playersInGroup) {
                    // 向客户端发送游戏id，玩家编号以及游戏所需要的玩家人数
                    eachPlayer.setCurrentStatus(GameStatus.PLAYING);
//                    echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
                    echoMessage.setResult(GAME_CREATE);
                    echoMessage.setContent(
                            eachPlayer.getGameId() + "~"
                            + eachPlayer.getCurrentNumber() + "~"
                            + FightLandlordGame.PLAYER_COGAME_NUMBER);
                    sessionWrite(eachPlayer.getIosession(), echoMessage);
                }
                // 根据当前触发游戏开始的玩家所携带的游戏id来取得游戏实例
                FightLandlordGame game = GamePool.getGame(gameId, FightLandlordGame.class);
                List<Player> playersInGame = game.getPlayers();
                // 开始洗牌与发牌，排序功能与出牌规则在客户端完成
                boolean isFirstOut = false;
                FightLandlordPoker[][] eachShuffledPokers = FightLandlordPoker.shuffle(null);
                // 取得合作玩家手中所持有的牌数
                String pokerNumberOfEachPlayer = "";
                for (int index = 0; index < eachShuffledPokers.length; index++) {
                    int lastIndex = eachShuffledPokers[index].length - 1;
                    pokerNumberOfEachPlayer += index + "=";
                    if (eachShuffledPokers[index][lastIndex] == null) {
                        pokerNumberOfEachPlayer += (eachShuffledPokers[index].length - 1) + ",";
                    } else {
                        pokerNumberOfEachPlayer += eachShuffledPokers[index].length + ",";
                    }
                }
                pokerNumberOfEachPlayer = pokerNumberOfEachPlayer.replaceFirst(",$", "");
                // 准备发牌开始游戏
                String firstPlayerNumber = null;
                StringBuilder builderTemp = new StringBuilder();
                String playerCards[] = new String[eachShuffledPokers.length];
                for (int m = 0; m < eachShuffledPokers.length; m++) {
                    StringBuilder builder = new StringBuilder();
                    for (int n = 0; n < eachShuffledPokers[m].length; n++) {
                        builderTemp.append(eachShuffledPokers[m][n].getValue() + ",");
                        builder.append(eachShuffledPokers[m][n].getValue() + ",");
                    }
                    playerCards[m] = builder.toString();
                }
                // 由于斗地主在发牌前会扣掉三张底牌，所以可能会将首发牌标志牌(红桃3)扣掉。
                // 确定开始首次发牌标识
                // 判断当前17 * 3 的扑克中是否包括发牌标识
                String currentAllCard = builderTemp.toString();
                boolean boolPK = false;
                // 是否包括红桃3标识牌
                String startPorker = FightLandlordGame.START_POKER.getValue();
                if (currentAllCard.matches("^.*" + startPorker + ".*$")) {
                    boolPK = true;
                }
                // 是否包括方块3标识牌
                if (!boolPK && currentAllCard.matches("^.*" + FightLandlordGame.START_POKER_DIAMOND.getValue() + ".*$")) {
                    startPorker = FightLandlordGame.START_POKER_DIAMOND.getValue();
                    boolPK = true;
                }
                // 是否包括黑桃3标识牌
                if (!boolPK && currentAllCard.matches("^.*" + FightLandlordGame.START_POKER_SPADE.getValue() + ".*$")) {
                    startPorker = FightLandlordGame.START_POKER_SPADE.getValue();
                    boolPK = true;
                }
                // 不包括前三种花色则直接设定梅花3为首发牌标识
                if (!boolPK) {
                    startPorker = FightLandlordGame.START_POKER_CLUB.getValue();
                }
                for (int x = 0; x < eachShuffledPokers.length; x++) {
                    // 为每位玩家发牌
//                    echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
                    echoMessage.setResult("GAME_GAME_STARTED");
                    echoMessage.setContent(playerCards[x].replaceFirst(",$", "~"));
                    sessionWrite(playersInGame.get(x).getIosession(), echoMessage);
                    // 记录游戏初始时玩家手中的牌信息
                    game.appendGameRecord(echoMessage.getContent());
                    if (!isFirstOut && playerCards[x].indexOf(startPorker) > -1) {
                        // 如果当前尚未设置过首次发牌的玩家，并且在当前牌序中发现标识牌，则确定为首次发牌的玩家
                        firstPlayerNumber = playersInGame.get(x).getCurrentNumber();
                        isFirstOut = true;
                    }
                }
                // 广播首次发牌玩家并将各个玩家初始牌发送到各个玩家手中，以便游戏结束亮牌用
                for (Player eachPlayer : playersInGame) {
                    //echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
                    echoMessage.setContent(firstPlayerNumber + "~" + game.getGameRecord());
                    echoMessage.setResult(GAME_FIRST_PLAY);
                    sessionWrite(eachPlayer.getIosession(), echoMessage);
                }
                for (Player eachPlayer : playersInGroup) {
                    // 更改玩家状态
                    eachPlayer.setCurrentStatus(GameStatus.PLAYING);
                }
                playersInGroup.clear();
            }
        }
    }

    @Override
    public void GAME_SETTING(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        // 在游戏开始前进行本次设置[不叫|1分|2分|3分]
        Player currentPlayer = ModelUtil.getPlayer(session);
        FightLandlordGame game = GamePool.getGame(currentPlayer.getGameId(), FightLandlordGame.class);
        List<Player> players = game.getPlayers();
        synchronized (players) {
            Iterator<Player> itr = players.iterator();
            while (itr.hasNext()) {
                Player player = itr.next();
                if (currentPlayer.equals(player)) {
                    continue;
                }
                //echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
                echoMessage.setResult(GAME_SETTING_UPDATE);
                echoMessage.setContent(message.getContent());
                sessionWrite(player.getIosession(), echoMessage);
            }
        }
        // 记录当前牌序
        game.appendGameRecord(message.getContent());
    }

    public void GAME_BOMB(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        // 在游戏过程中出牌翻倍
        Player currentPlayer = ModelUtil.getPlayer(session);
        FightLandlordGame game = GamePool.getGame(currentPlayer.getGameId(), FightLandlordGame.class);
        List<Player> players = game.getPlayers();
        String[] results = message.getContent().split("~");
        // 判断是否有炸弹，火箭
        // 地主把牌出完，其余两家一张牌都没出，分数×2 ；
        // 两家中有一家出完牌，而地主仅仅出过一手牌，分数×2 。
        if (results.length == 4 && "double".equals(results[3])) {
            game.addMultiple();
        }
        synchronized (players) {
            for (Player eachPlayer : players) {
                //echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
                echoMessage.setResult(GAME_BOMB);
                echoMessage.setContent(message.getContent() + "~" + game.getMultiple());
                sessionWrite(eachPlayer.getIosession(), echoMessage);
            }
        }
    }

    @Override
    public void GAME_SETTING_FINISH(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        // 玩家游戏设置结束
        Player currentPlayer = ModelUtil.getPlayer(session);
        FightLandlordGame game = GamePool.getGame(currentPlayer.getGameId(), FightLandlordGame.class);
        String[] results = message.getContent().split("~");
        // 游戏最终设置的玩家序号，首次发牌玩家序号
        String playerNumber = results[0];
        // 当前游戏设置
        int settingValue = Integer.parseInt(results[1]);
        FightLandlordGameSetting setting = FightLandlordGameSetting.fromOrdinal(settingValue);
        setting.setPlayerNumber(playerNumber);
        game.setSetting(setting);
        List<Player> players = game.getPlayers();
        synchronized (players) {
            for (Player eachPlayer : players) {
                //echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
                echoMessage.setResult(GAME_SETTING_OVER);
                echoMessage.setContent(playerNumber + "~" + settingValue);
                sessionWrite(eachPlayer.getIosession(), echoMessage);
            }
        }
        log.debug(setting);
    }

    public void GAME_SETTING_UPDATE_FINISH(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        // 玩家游戏设置结束
        Player currentPlayer = ModelUtil.getPlayer(session);
        FightLandlordGame game = GamePool.getGame(currentPlayer.getGameId(), FightLandlordGame.class);
        String[] results = message.getContent().split("~");
        // 游戏最终设置的玩家序号，首次发牌玩家序号
        String playerNumber = results[0];
        // 为地主发底牌,并为其它两家显示底牌
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < FightLandlordPoker.handlePokers.length; i++) {
            builder.append(FightLandlordPoker.handlePokers[i].getValue() + ",");
        }
        List<Player> players = game.getPlayers();
        synchronized (players) {
            for (Player player : players) {
                //echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
                echoMessage.setResult(GAME_SETTING_UPDATE_FINISH);
                echoMessage.setContent(builder.toString().replaceFirst(",$", "~") + playerNumber);
                sessionWrite(player.getIosession(), echoMessage);
            }
        }
        // 记录底牌
        game.appendGameRecord(echoMessage.getContent());
    }

    @Override
    public void GAME_BRING_OUT(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        // 向游戏中的其他玩家发送消息
        Player currentPlayer = ModelUtil.getPlayer(session);
        FightLandlordGame game = GamePool.getGame(currentPlayer.getGameId(), FightLandlordGame.class);

        List<Player> players = game.getPlayers();
        synchronized (players) {
            Iterator<Player> itr = players.iterator();
            while (itr.hasNext()) {
                Player player = itr.next();
                if (currentPlayer.equals(player)) {
                    continue;
                }
                //echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
                echoMessage.setResult(GAME_BRING_OUT);
                echoMessage.setContent(message.getContent());
                sessionWrite(player.getIosession(), echoMessage);
            }
            // 记录当前牌序
            game.appendGameRecord(message.getContent());
        }
    }

    @Override
    public void GAME_WIN(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        // 向游戏中的其他玩家发送消息
        Player currentPlayer = ModelUtil.getPlayer(session);
        FightLandlordGame game = GamePool.getGame(currentPlayer.getGameId(), FightLandlordGame.class);
        // 判断是否为最终获胜
        if (!FightLandlordGameSetting.NO_RUSH.equals(game.getSetting())) {
            // 立即结束当前游戏
            GAME_WIN_AND_END(session, message, echoMessage);
            return;
        } else {
            game.addWinnerNumber(String.valueOf(currentPlayer.getCurrentNumber()));
            List<Player> players = game.getPlayers();
            synchronized (players) {
                Iterator<Player> itr = players.iterator();
                while (itr.hasNext()) {
                    Player player = itr.next();
                    if (currentPlayer.equals(player)) {
                        continue;
                    }
                    //echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
                    echoMessage.setResult(GAME_WINNER_PRODUCED);
                    echoMessage.setContent(message.getContent());
                    sessionWrite(player.getIosession(), echoMessage);
                }
                // 记录当前牌序
                game.appendGameRecord(message.getContent());
            }
        }
    }

    public void GAME_WIN_OVER(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        // 向游戏中的其他玩家发送消息
        Player currentPlayer = ModelUtil.getPlayer(session);
        FightLandlordGame game = GamePool.getGame(currentPlayer.getGameId(), FightLandlordGame.class);
        // 判断是否为最终获胜  
//        game.addWinnerNumber(String.valueOf(currentPlayer.getCurrentNumber()));
        List<Player> players = game.getPlayers();
       /* synchronized (players) {
            Iterator<Player> itr = players.iterator();
            while (itr.hasNext()) {
                Player player = itr.next();
                if (currentPlayer.equals(player)) {
                    continue;
                }
                //echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
                echoMessage.setResult("GAME_WINNER_PRODUCED_NOTIFY");
                echoMessage.setContent("{\"win\":" + currentPlayer.getPos() + "}");
                sessionWrite(player.getIosession(), echoMessage);
            }
            // 记录当前牌序
//            game.appendGameRecord(message.getContent());
        }*/
        // 保存游戏积分
        //game.persistScore();
        int landlord = game.getMaxCallScorePos();
        log.info("开始统计总分");
        // 显示游戏积分
        Iterator<Player> itr = players.iterator();
        // 构造积分显示信息
        String json = "{\"win\":" + currentPlayer.getPos();
        while (itr.hasNext()) {
            Player player = itr.next();
            player.setCurrentStatus(GameStatus.IDLE);
            //地主赢
            int countScore = 0;
            if (currentPlayer.getPos() == landlord) {
                if (player.getPos() == landlord) {
                    countScore = game.getMaxCallScore() * game.getMultiple() * 2;
                } else {
                    countScore = -game.getMaxCallScore() * game.getMultiple();
                }
            } else {
                if (player.getPos() == landlord) {
                    countScore = -game.getMaxCallScore() * game.getMultiple() * 2;
                } else {
                    countScore = game.getMaxCallScore() * game.getMultiple();
                }
            }
            player.setScore(player.getScore() + countScore);//全局积分
            player.setLastGameScore(countScore);//本局积分
            player.setTotalGameScore(player.getTotalGameScore() + countScore);//三个人累积积分
            json += ",\"" + player.getPos() + "\":" + countScore;
            json += ",\"" + player.getPos() + "total\":" + player.getTotalGameScore();
        }
        json += "}";
        echoMessage.setResult("GAME_OVER_NOTIFY");
        echoMessage.setContent(json);
        Iterator<Player> itr1 = players.iterator();
        while (itr1.hasNext()) {
            Player player = itr1.next();
            player.setState(2);
            player.setCurrentStatus(GameStatus.IDLE);
            sessionWrite(player.getIosession(), echoMessage);
        }
        //游戏资料重置
        game.setMaxCallScore(0);
        game.setMaxCallScorePos(0);
        game.setFirstPlayerNumber(0);
        game.setPassCardCount(0);
        game.setLastPlayCardpos(0);
    }

    @Override
    @HibernateTransactionSupport
    public void GAME_WIN_AND_END(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        // 游戏结束，向游戏中的其他玩家发送消息
        Player currentPlayer = ModelUtil.getPlayer(session);
        FightLandlordGame game = GamePool.getGame(currentPlayer.getGameId(),
                FightLandlordGame.class);
        String[] results = message.getContent().split("~");
        List<Player> players = game.getPlayers();
        log.debug(game.getSetting().getDisplayName());
        // 记录当前牌序
        game.appendGameRecord(message.getContent());
        synchronized (players) {
            // 设置名次并计算积分
            if (FightLandlordGameSetting.NO_RUSH.equals(game.getSetting())) {
                // 1分，添加获胜者
                game.addWinnerNumber(results[0]);
            } else if (FightLandlordGameSetting.ONE_RUSH.equals(game.getSetting())) {
                // 1分，添加获胜者
                game.addWinnerNumber(results[0]);
            } else if (FightLandlordGameSetting.TWO_RUSH.equals(game.getSetting())) {
                // 2分，添加获胜者
                game.addWinnerNumber(results[0]);
            } else if (FightLandlordGameSetting.THREE_RUSH.equals(game.getSetting())) {
                // 3分，添加获胜者
                game.addWinnerNumber(results[0]);
            }
            // 保存游戏积分
            game.persistScore();
            // 显示游戏积分
            Iterator<Player> itr = players.iterator();
            // 构造积分显示信息
            String content = message.getContent();
            while (itr.hasNext()) {
                Player player = itr.next();
                player.setCurrentStatus(GameStatus.IDLE);
                //echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
                echoMessage.setResult(GAME_OVER);
                echoMessage.setContent(content + "~" + game.getGameDetailScore(player.getCurrentNumber()));
                sessionWrite(player.getIosession(), echoMessage);
            }
        }
        // 清除内存中本次游戏的相关信息
        log.debug(game.getGameRecord());
        log.debug(game.getWinnerNumbers());
        GamePool.distroyGame(currentPlayer.getGameId(), FightLandlordGame.class);
    }

    @Override
    public void GAME_PLAYER_LOST_CONNECTION(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        // 通知其他玩家并为其他玩家分配分数
        Player player = ModelUtil.getPlayer(session);
        if (GamePool.getGame(player.getGameId(), FightLandlordGame.class) != null) {
            // 扣除玩家分数，并为游戏中的其他玩家分配分数
            // TODO
        } else {
            // 非游戏中掉线的情况，通知其他玩家在线人数发生了变化
            PlatformMessage localMessage = (PlatformMessage) F3ServerMessage.createInstance(MessageType.PLATFORM);
            new PlatformInMessageHandler().PLATFORM_PLAYER_LOST_CONNECTION(session, localMessage, localMessage.getEchoMessage());
        }
    }

    @Override
    public void GAME_CHEAT_FOUND(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        Player currentPlayer = ModelUtil.getPlayer(session);
        echoMessage.setResult("GAME_CHEAT_FOUND");
        echoMessage.setContent(message.getContent());
        sessionWrite(session, echoMessage);
    }

    public void GAME_SNED_MESSAGE(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        //
        Player currentPlayer = ModelUtil.getPlayer(session);
        String results[] = message.getContent().split("~");
        echoMessage.setResult("GAME_RECEIVER_MESSAGE_NOTIFY");
        String json = "{\"msg\":\"" + results[0] + "\"," + "\"user\":\"" + currentPlayer.getUserId() + "\",\"date\":\"" + DateUtil.formatNow() + "\",\"color\":" + results[1] + "}";
        echoMessage.setContent(json);
        Player roomplayer;
        Set<String> players = currentPlayer.getParent().getChildren().keySet();
        for (String p : players) {
            roomplayer = currentPlayer.getParent().getChildren().get(p);
            //如果不是当前用户，则通知有玩家加入                    
            if (!p.equals(currentPlayer.getPos())) {
                roomplayer.getIosession().write(EncryptionUtil.Base64Encode(HandlerDispatcher.respondMessage(echoMessage)));
                log.info("向:" + roomplayer.getUserId() + " 本房间玩家发送通知聊天内容:" + json);
            }
        }
//        NoticeRoomPlayer(currentPlayer.getParent(), currentPlayer, String.valueOf(currentPlayer.getPos()), echoMessage, "GAME_RECEIVER_MESSAGE_NOTIFY", json);
    }

    public void GAME_SNED_CARDS(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        Player currentPlayer = ModelUtil.getPlayer(session);
        //先检查玩家是不是没有准备，没有开始游戏,是的话，不鸟他的消息
        if (currentPlayer.getState() < 3) {
            return;
        }
//        boolean allReady = true;

        FightLandlordGame game = GamePool.getGame(currentPlayer.getGameId(), FightLandlordGame.class);
        if (game == null) {
            return;
        }
        List<Player> playersInGame = game.getPlayers();
        int currentpos = GetLeftRightPos(false, currentPlayer.getPos());
        //{"cards"}
        //如果玩家不出
        String issend = "true";
        String results[] = message.getContent().split("~");
        if (game.getPassCardCount() == 0) {
            if ("pass".equals(results[0])) {
                game.setPassCardCount(1);

            }
        } else if (game.getPassCardCount() == 1) {
            if ("pass".equals(results[0])) {
                game.setPassCardCount(2);
            } else {
                game.setPassCardCount(0);
            }
        }
        if ("pass".equals(results[0])) {
            issend = "false";
        }
        String cardindex = results[1];
//        if (results.length == 2 && "double".equals(results[1])) {
//            game.addMultiple();
//            cardindex = "false";
//        }
        //炸弹
        if (ConvertUtil.toInt(results[1]) >= 3 && ConvertUtil.toInt(results[1]) <= 7) {
            game.addMultiple();
        }
        if (game.getPassCardCount() >= 2) {
            game.setPassCardCount(0);
            echoMessage.setResult("GAME_MUST_SEND_NOTIFY");
            String json = "{\"currentpos\":" + currentpos + ",\"lastpost\":" + currentPlayer.getPos() + ",\"issend\":" + issend + ",\"lastcards\":\"" + results[0] + "\",\"memo\":" + game.getMaxCallScore() + ",\"cardindex\":" + cardindex + "}";
            echoMessage.setContent(json);
            sessionWrite(session, echoMessage);
            for (Player eachPlayer : playersInGame) {
                if (eachPlayer.getPos() != currentPlayer.getPos()) {
                    sessionWrite(eachPlayer.getIosession(), echoMessage);
                }
            }
        } else {
            //            game.setPassCardCount(0);
            String json = "{\"currentpos\":" + currentpos + ",\"lastpost\":" + currentPlayer.getPos() + ",\"issend\":" + issend + ",\"lastcards\":\"" + results[0] + "\",\"memo\":" + game.getMaxCallScore() + ",\"cardindex\":" + cardindex + "}";
            echoMessage.setResult("GAME_TURNTO_PALY_NOTIFY");
            echoMessage.setContent(json);
            sessionWrite(session, echoMessage);
            for (Player eachPlayer : playersInGame) {
                if (eachPlayer.getPos() != currentPlayer.getPos()) {
                    sessionWrite(eachPlayer.getIosession(), echoMessage);
                }
            }
            if (issend == "true") {
                game.setLastPlayCardpos(currentpos);
            }
        }

    }

    public void GAME_CALL_SCORE(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        Player currentPlayer = ModelUtil.getPlayer(session);
        //先检查玩家是不是没有准备，没有开始游戏,是的话，不鸟他的消息
        if (currentPlayer.getState() < 3) {
            return;
        }
//        boolean allReady = true;

        FightLandlordGame game = GamePool.getGame(currentPlayer.getGameId(), FightLandlordGame.class);
        if (game == null) {
            return;
        }
        if (game.getFirstPlayerNumber() == 0) {
            game.setFirstPlayerNumber(currentPlayer.getPos());
        }
        List<Player> playersInGame = game.getPlayers();
        int score = ConvertUtil.toInt(message.getContent());
        int currentpos = GetLeftRightPos(false, currentPlayer.getPos());
        String iscall = "false";
        if (score > 0) {
            iscall = "true";
        } else {
            game.setPassCardCount(game.getPassCardCount() + 1);
        }
        //生成地主了，  
        if (score == 3) {
            currentpos = 4;
            String json = "{\"currentpos\":" + currentpos + ",\"lastpost\":" + currentPlayer.getPos() + ",\"iscall\":" + iscall + ",\"score\":" + score + ",\"maxcallscore\":" + game.getMaxCallScore() + "}";
            echoMessage.setResult("GAME_CALL_SCORE_NOTIFY");
            echoMessage.setContent(json);
            sessionWrite(session, echoMessage);
            for (Player eachPlayer : playersInGame) {
                if (eachPlayer.getPos() != currentPlayer.getPos()) {
                    sessionWrite(eachPlayer.getIosession(), echoMessage);
                }
            }

            game.setMaxCallScore(3);
            game.setMaxCallScorePos(currentPlayer.getPos());//设置地主
            game.setPassCardCount(0);
            log.info("房间:" + currentPlayer.getRoomid() + ",产生地主:" + currentPlayer.getUserId());
            json = "{\"landlordpos\":" + currentPlayer.getPos() + ",\"threecards\":\"" + game.GetHandlePokers() + "\",\"lastpost\":" + currentPlayer.getPos() + ",\"iscall\":" + iscall + ",\"score\":" + score + ",\"maxcallscore\":3,\"mutilple\":1}";
            echoMessage.setResult("GAME_BE_LANDLORD_NOTIFY");
            echoMessage.setContent(json);
            for (Player eachPlayer : playersInGame) {
                sessionWrite(eachPlayer.getIosession(), echoMessage);
            }
        } else if (currentpos == game.getFirstPlayerNumber()) {
            currentpos = 4;
            String json = "{\"currentpos\":" + currentpos + ",\"lastpost\":" + currentPlayer.getPos() + ",\"iscall\":" + iscall + ",\"score\":" + score + ",\"maxcallscore\":" + game.getMaxCallScore() + "}";
            echoMessage.setResult("GAME_CALL_SCORE_NOTIFY");
            echoMessage.setContent(json);
            sessionWrite(session, echoMessage);
            for (Player eachPlayer : playersInGame) {
                if (eachPlayer.getPos() != currentPlayer.getPos()) {
                    sessionWrite(eachPlayer.getIosession(), echoMessage);
                }
            }
            //大家都不叫
            if (game.getPassCardCount() == 3) {
                //重新发牌
                GAME_FIRST_PLAY(session, message, echoMessage);
                game.setPassCardCount(0);
            } //取叫分最大的那个人
            else {
                //本次叫分比最后叫分人多，更新游戏最后叫分
                if (score > game.getMaxCallScore()) {
                    game.setMaxCallScore(score);
                    game.setMaxCallScorePos(currentPlayer.getPos());//设置地主
                    log.info("房间:" + currentPlayer.getRoomid() + ",产生地主:" + currentPlayer.getUserId());
                }
                if (game.getMaxCallScore() < 1) {
                    GAME_FIRST_PLAY(session, message, echoMessage);
                } else {
                    json = "{\"landlordpos\":" + game.getMaxCallScorePos() + ",\"threecards\":\"" + game.GetHandlePokers() + "\",\"lastpost\":" + currentPlayer.getPos() + ",\"iscall\":" + iscall + ",\"score\":" + score + ",\"maxcallscore\":" + game.getMaxCallScore() + ",\"mutilple\":" + "1" + "}";
                    echoMessage.setResult("GAME_BE_LANDLORD_NOTIFY");
                    game.setPassCardCount(0);
                    echoMessage.setContent(json);
                    for (Player eachPlayer : playersInGame) {
                        sessionWrite(eachPlayer.getIosession(), echoMessage);
                    }
                }
            }
        } else {
            //本次叫分比最后叫分人多，更新游戏最后叫分
            if (score > game.getMaxCallScore()) {
                game.setMaxCallScore(score);
                game.setMaxCallScorePos(currentPlayer.getPos());//设置地主
            }
            String json = "{\"currentpos\":" + currentpos + ",\"lastpost\":" + currentPlayer.getPos() + ",\"iscall\":" + iscall + ",\"score\":" + score + ",\"maxcallscore\":" + game.getMaxCallScore() + "}";
            echoMessage.setResult("GAME_CALL_SCORE_NOTIFY");
            echoMessage.setContent(json);
            sessionWrite(session, echoMessage);
            for (Player eachPlayer : playersInGame) {
                if (eachPlayer.getPos() != currentPlayer.getPos()) {
                    sessionWrite(eachPlayer.getIosession(), echoMessage);
                }
            }
        }


    }

    public int GetLeftRightPos(boolean isLeft, int currentPos) {
        int pos = 0;
        if (isLeft) {
            pos = currentPos - 1;
            if (pos == 0) {
                pos = 3;
            }
        } else {
            pos = currentPos + 1;
            if (pos > 3) {
                pos = 1;
            }
        }
        return pos;
    }

    public void GAME_ROOM_READY(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {

        Player player = (Player) session.getAttribute(Player.ATTR_NAME);
        player.setState(3);// room ready
        player.setReady(true);
        log.info("玩家准备完毕：" + player.getUserId());
        echoMessage.setResult("GAME_ROOM_READY");
        echoMessage.setContent("{\"success\":true}");
        sessionWrite(session, echoMessage);
        //给其他玩家发送准备消息
        NoticeRoomPlayer(player.getParent(), player, String.valueOf(player.getPos()), echoMessage, "GAME_ROOM_PLAYER_READY", "{\"rid\":" + player.getRoomid() + ",\"pos\":" + player.getPos() + "}");

        NoticeLobbyPlayer(player, echoMessage, "NOTICE_LOBBY_ROOM_USER_READY", null);
        //判断玩家是否全部准备，则可以开始游戏
        boolean allReady = true;
        int count = 0;
        Room room = player.getParent();
        Set<String> players = room.getChildren().keySet();
        Player roomplayer;
        String playernames = "";
        List<Player> playersInGroup = new ArrayList<Player>();
        for (String p : players) {
            roomplayer = room.getChildren().get(p);
            if (roomplayer.getState() < 3) {
                allReady = false;
                return;
            } else {
                count++;
            }
            playersInGroup.add(roomplayer);
            playernames += roomplayer.getUserId() + ",";
        }
        if (count != 3) {
            return;
        }
        // 根据玩家当前的所在的房间进来开始游戏
        log.info("房间三人已准备，开始游戏,roomid:" + player.getRoomid() + ",房间人：" + playernames);
        GAME_FIRST_PLAY(session, message, echoMessage);

    }

    public void GAME_FIRST_PLAY(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        Player player = (Player) session.getAttribute(Player.ATTR_NAME);
        Room room = player.getParent();
        Set<String> players = room.getChildren().keySet();
        Player roomplayer;
        List<Player> playersInGroup = new ArrayList<Player>();
        for (String p : players) {
            roomplayer = room.getChildren().get(p);
            playersInGroup.add(roomplayer);
        }
        String gameId;
        if (GamePool.getGame(player.getGameId(), FightLandlordGame.class) == null) {
            player.setLastGameScore(0);//本局积分
            player.setTotalGameScore(0);//三个人累积积分
            gameId = GamePool.prepareFightLandlordGame(playersInGroup);
        } else {
            gameId = player.getGameId();
        }
        FightLandlordGame game = GamePool.getGame(gameId, FightLandlordGame.class);
        game.setPassCardCount(0);
        List<Player> playersInGame = game.getPlayers();
        // 开始洗牌与发牌，排序功能与出牌规则在客户端完成
        boolean isFirstOut = false;
        FightLandlordPoker[][] eachShuffledPokers = FightLandlordPoker.shuffle(game);
        // 取得合作玩家手中所持有的牌数
//        String pokerNumberOfEachPlayer = "";
//        for (int index = 0; index < eachShuffledPokers.length; index++) {
//            int lastIndex = eachShuffledPokers[index].length - 1;
//            pokerNumberOfEachPlayer += index + "=";
//            if (eachShuffledPokers[index][lastIndex] == null) {
//                pokerNumberOfEachPlayer += (eachShuffledPokers[index].length - 1) + ",";
//            } else {
//                pokerNumberOfEachPlayer += eachShuffledPokers[index].length + ",";
//            }
//        }
//        pokerNumberOfEachPlayer = pokerNumberOfEachPlayer.replaceFirst(",$", "");
        // 准备发牌开始游戏
        String firstPlayerNumber = null;
        StringBuilder builderTemp = new StringBuilder();
        String playerCards[] = new String[eachShuffledPokers.length];
        for (int m = 0; m < eachShuffledPokers.length; m++) {
            StringBuilder builder = new StringBuilder();
            for (int n = 0; n < eachShuffledPokers[m].length; n++) {
                builderTemp.append(eachShuffledPokers[m][n].getValue() + ",");
                builder.append(eachShuffledPokers[m][n].getValue() + ",");
            }
            playerCards[m] = builder.toString();
        }
        // 由于斗地主在发牌前会扣掉三张底牌，所以可能会将首发牌标志牌(红桃3)扣掉。
        // 确定开始首次发牌标识
        // 判断当前17 * 3 的扑克中是否包括发牌标识
        String currentAllCard = builderTemp.toString();
        boolean boolPK = false;
        // 是否包括红桃3标识牌
        String startPorker = FightLandlordGame.START_POKER.getValue();
        if (currentAllCard.matches("^.*" + startPorker + ".*$")) {
            boolPK = true;
        }
        // 是否包括方块3标识牌
        if (!boolPK && currentAllCard.matches("^.*" + FightLandlordGame.START_POKER_DIAMOND.getValue() + ".*$")) {
            startPorker = FightLandlordGame.START_POKER_DIAMOND.getValue();
            boolPK = true;
        }
        // 是否包括黑桃3标识牌
        if (!boolPK && currentAllCard.matches("^.*" + FightLandlordGame.START_POKER_SPADE.getValue() + ".*$")) {
            startPorker = FightLandlordGame.START_POKER_SPADE.getValue();
            boolPK = true;
        }
        // 不包括前三种花色则直接设定梅花3为首发牌标识
        if (!boolPK) {
            startPorker = FightLandlordGame.START_POKER_CLUB.getValue();
        }
        String json = "{";
//        String json="{\"firstpos\":2,\"1\":{\"cards\":\"12,121\",\"cardnumber\":17}}";
        for (int x = 0; x < eachShuffledPokers.length; x++) {
            // 为每位玩家发牌
//                    echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
//            echoMessage.setResult("GAME_GAME_STARTED");
//            echoMessage.setContent(playerCards[x].replaceFirst(",$", "~"));
//            sessionWrite(playersInGame.get(x).getIosession(), echoMessage);
            // 记录游戏初始时玩家手中的牌信息
            if (x != 0) {
                json += ",";
            }
            json += "\"" + playersInGame.get(x).getPos() + "\":{\"cards\":\"" + playerCards[x].replaceFirst(",$", "") + "\",\"cardnumber\":17}";
            game.appendGameRecord(playerCards[x].replaceFirst(",$", "~"));
            if (!isFirstOut && playerCards[x].indexOf(startPorker) > -1) {
                // 如果当前尚未设置过首次发牌的玩家，并且在当前牌序中发现标识牌，则确定为首次发牌的玩家
                firstPlayerNumber = String.valueOf(playersInGame.get(x).getPos());
                isFirstOut = true;
            }
        }
        json += ",\"firstpos\":" + firstPlayerNumber + "}";

        echoMessage.setContent(json);
        echoMessage.setResult("GAME_FIRST_PLAY");
        // 广播首次发牌玩家并将各个玩家初始牌发送到各个玩家手中，以便游戏结束亮牌用
        for (Player eachPlayer : playersInGame) {
            sessionWrite(eachPlayer.getIosession(), echoMessage);
        }
        for (Player eachPlayer : playersInGroup) {
            // 更改玩家状态
            eachPlayer.setCurrentStatus(GameStatus.PLAYING);
            //分数清零
            eachPlayer.setTotalGameScore(0);
            eachPlayer.setLastGameScore(0);
        }
        playersInGroup.clear();
        NoticeLobbyPlayer(player, echoMessage, "NOTICE_LOBBY_ROOM_GAME_START", "{\"rid\":" + player.getRoomid() + "}");
    }

    public void GAME_ROOM_JOIN(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        String results[] = message.getContent().split("~");
        Player player = (Player) session.getAttribute(Player.ATTR_NAME);
//        String userId = player.getUserId();
        String roomid = results[0];
        String pos = results[1];
        if (!"1".equals(pos) && !"2".equals(pos) && !"3".equals(pos) && !"-1".equals(pos)) {
            echoMessage.setResult("GAME_ROOM_JOIN");
            echoMessage.setContent("{\"success\":false,\"message\":\"pos is not 1,2,3\"}");
            sessionWrite(session, echoMessage);
            return;
        }
        String json;
        int count = 0;
        Room room = ModelUtil.getPlatform().getChild("1").getChild(roomid);
        if (room != null) {
            //位置没有人
            if ("-1".equals(pos)) {
                if (ModelUtil.getPlatform().getChild("1").getChild(roomid).getChild("1") == null) {
                    pos = "1";
                } else if (ModelUtil.getPlatform().getChild("1").getChild(roomid).getChild("2") == null) {
                    pos = "2";
                } else if (ModelUtil.getPlatform().getChild("1").getChild(roomid).getChild("3") == null) {
                    pos = "3";
                } else {
                    echoMessage.setResult("GAME_ROOM_JOIN");
                    echoMessage.setContent("{\"success\":false,\"message\":\" 1,2,3 have player ,please change other table\"}");
                    sessionWrite(session, echoMessage);
                    return;
                }
            }
            if (room.getChild(pos) == null) {

                player.setPos(ConvertUtil.toInt(pos));
                player.setParent(room);
                player.setState(2);//room not ready
                player.setRoomid(roomid);
                //当前玩家json信息，发送给其他玩家
                ModelUtil.getPlatform().getChild("1").getChild(roomid).addChild(pos, player);
                //返回房间玩家json
//                json = "{\"rid\":" + roomid + "}";
                json = "{\"rid\":" + roomid + ",\"pos\":" + pos + ",\"players\":{";
                Set<String> players = room.getChildren().keySet();
                Player roomplayer;
                for (String p : players) {
                    roomplayer = room.getChildren().get(p);
                    //如果不是当前用户，则通知有玩家加入                    
                    if (!p.equals(pos)) {
                        echoMessage.setResult("GAME_ROOM_PLAYER_JOIN");
                        echoMessage.setContent(GetPlayerInfoByJson(player));
                        sessionWrite(roomplayer.getIosession(), echoMessage);
                        log.info("本房间玩家加入房间通知:" + roomplayer.getUserId() + ",玩家加入:" + player.getUserId());
                    }
                    if (count != 0) {
                        json += ",";
                    }
                    json += "\"" + roomplayer.getPos() + "\":{\"pid\":\"" + roomplayer.getId() + "\",\"pos\":" + roomplayer.getPos() + ",\"name\":\"" + roomplayer.getName() + "\"";
                    json += ",\"score\":" + roomplayer.getScore();
                    json += ",\"money\":" + roomplayer.getMoney();
                    json += ",\"avatar\":\"" + roomplayer.getAvatar() + "\"";
                    json += ",\"ready\":" + roomplayer.isReady();
                    json += "}";
                    count++;
                }
                json += "}}";
//                json = "{\"rid\":" + roomid + ",\"pos\":" + pos + "}";
            } else {
                json = "{\"success\":false,\"message\":\"pos have player\"}";
            }
        } else {
            json = "{\"success\":false,\"message\":\"room not find\"}";
        }
        log.info("用户加入房间：" + json);
        //echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
        player.setState(2);
        echoMessage.setResult("GAME_ROOM_JOIN");
        echoMessage.setContent(json);
        sessionWrite(session, echoMessage);

        //通知大厅，玩家加入房间      
        NoticeLobbyPlayer(player, echoMessage, "NOTICE_LOBBY_ROOM_USER_JOIN", null);
    }

    private void NoticeLobbyPlayer(Player currentPlayer, EchoMessage echoMessage, String dispatchEvent, String jsonInfo) {
        Set<IoSession> sessions = ModelUtil.getSessions();
        echoMessage.setResult(dispatchEvent);
        if (jsonInfo == null) {
            echoMessage.setContent(GetPlayerInfoByJson(currentPlayer));
        } else {
            echoMessage.setContent(jsonInfo);
        }
        synchronized (sessions) {
            Iterator<IoSession> itr = sessions.iterator();
            while (itr.hasNext()) {
                IoSession currentSession = itr.next();
                Player loginplayer = (Player) currentSession.getAttribute(Player.ATTR_NAME);
                //大厅的玩家发通知
                if (loginplayer != null && loginplayer.getState() < 2) {

                    sessionWrite(loginplayer.getIosession(), echoMessage);
                    log.info("大厅玩家发送通知:" + loginplayer.getUserId() + "," + dispatchEvent + ",json:" + echoMessage.getContent());
                }
            }
        }
    }

    private void NoticeRoomPlayer(Room room, Player currentPlayer, String currentpos, EchoMessage echoMessage, String dispatchEvent, String jsonInfo) {
        Player roomplayer;
        Set<String> players = room.getChildren().keySet();
        for (String p : players) {
            roomplayer = room.getChildren().get(p);
            //如果不是当前用户，则通知有玩家加入                    
            if (!p.equals(currentpos)) {
                echoMessage.setResult(dispatchEvent);
                if (jsonInfo == null) {
                    echoMessage.setContent(GetPlayerInfoByJson(currentPlayer));
                } else {
                    echoMessage.setContent(jsonInfo);
                }
                sessionWrite(roomplayer.getIosession(), echoMessage);
                log.info("本房间玩家发送通知:" + roomplayer.getUserId() + "," + dispatchEvent + ",json:" + echoMessage.getContent());
            }
        }
    }

    private String GetPlayerInfoByJson(Player roomplayer) {
        if (roomplayer == null) {
            return "{}";
        }
        String json = "{\"pid\":\"" + roomplayer.getId() + "\",\"pos\":" + roomplayer.getPos() + ",\"name\":\"" + roomplayer.getName() + "\"";
        json += ",\"rid\":" + roomplayer.getRoomid();
        json += ",\"pos\":" + roomplayer.getPos();
        json += ",\"state\":" + roomplayer.getState();
        json += ",\"score\":" + roomplayer.getScore();
        json += ",\"money\":" + roomplayer.getMoney();
        json += ",\"avatar\":\"" + roomplayer.getAvatar() + "\"";
        json += ",\"ready\":" + roomplayer.isReady();
        json += "}";
        return json;
    }

    public void LOBBY_PLAYER_LIST(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        String json = "{\"players\":[";
        int count = 0;
        PlayerResult playerRlt;
        for (IoSession ioSession : ModelUtil.getSessions()) {
            Player player = (Player) ioSession.getAttribute(Player.ATTR_NAME);
            if (player != null) {
                playerRlt = new PlayerResult(player.getId(), player.getName());
                playerRlt.setMoney(player.getCurrentScore());
                playerRlt.setScore(player.getCurrentScore());
                playerRlt.setPid(ConvertUtil.toInt(player.getId()));
                if (count == 0) {
                    json += gson.toJson(playerRlt);
                } else {
                    json += "," + gson.toJson(playerRlt);
                }
                count++;
            }
        }
        json += "]}";
        log.info(ModelUtil.getPlayer(session).getUserId() + "在线用户列表:");
        //echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
        echoMessage.setResult("LOBBY_PLAYER_LIST");
        echoMessage.setContent(json);
        sessionWrite(session, echoMessage);
    }

    public void GAME_ROOM_EXIT(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {
        Player currentPlayer = ModelUtil.getPlayer(session);
        String json;
        boolean isSuccess = false;
        String roomid = currentPlayer.getRoomid();
        String pos = String.valueOf(currentPlayer.getPos());
        String userId = currentPlayer.getUserId();
        Room room = ModelUtil.getPlatform().getChild("1").getChild(roomid);
        if (room != null) {
            Player player = room.getChild(pos);
            if (player != null && player.getUserId().equals(currentPlayer.getUserId())) {
                currentPlayer.setParent(null);
                currentPlayer.setState(1);
                // 清除内存中本次游戏的相关信息   
                Game<?> game = GamePool.getGame(currentPlayer.getGameId(), Game.class);
                if (game != null) {
                    GamePool.distroyGame(currentPlayer.getGameId(), FightLandlordGame.class);
                }
                currentPlayer.setGameId("-1");
                currentPlayer.setRoomid("");
                currentPlayer.setPos(0);
                currentPlayer.setReady(false);
                currentPlayer.setCurrentScore(0);
                currentPlayer.setTotalGameScore(0);
                ModelUtil.getPlatform().getChild("1").getChild(roomid).removeChild(pos);
                isSuccess = true;
                json = "{\"rid\":" + roomid + ",\"pos\":" + pos + "}";
                //给其他玩家发送退出消息
                NoticeRoomPlayer(room, currentPlayer, pos, echoMessage, "GAME_ROOM_PLAYER_EXIT", "{\"rid\":" + roomid + ",\"pos\":" + pos + "}");
            } else {
                json = "{\"success\":false,\"message\":\"pos have not player,or you are not stay the pos\"}";
            }
        } else {
            json = "{\"success\":false,\"message\":\"room not find\"}";
        }
        log.info("用户退出房间:");
//        echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
        echoMessage.setResult("GAME_ROOM_EXIT");
        echoMessage.setContent(json);
        sessionWrite(session, echoMessage);
        if (isSuccess) {
            NoticeLobbyPlayer(currentPlayer, echoMessage, "NOTICE_LOBBY_ROOM_USER_EXIT", "{\"rid\":" + roomid + ",\"pos\":" + pos + "}");
        }

    }

    public void LOBBY_TABLE_LIST(IoSession session, FightLandlordGameMessage message, EchoMessage echoMessage) throws Exception {

//        log.debug("LOBBY_TABLE_LIST收到消息;" + message.getContent());
//        echoMessage = F3ServerMessage.createInstance(MessageType.FIGHT_LANDLORD).getEchoMessage();
        echoMessage.setResult("LOBBY_TABLE_LIST");

        Map<String, Room> rooms = ModelUtil.getPlatform().getChild("1").getChildren();
        Room room;
        List<Room> roomsInQueue = new ArrayList<Room>();
        for (Room eachRoom : rooms.values()) {
            roomsInQueue.add(eachRoom);
        }
        Collections.sort(roomsInQueue, new Comparator<Room>() {

            public int compare(Room p1, Room p2) {
                if (ConvertUtil.toInt(p1.getId()) > ConvertUtil.toInt(p2.getId())) {
                    return 1;
                } else if (ConvertUtil.toInt(p1.getId()) < ConvertUtil.toInt(p2.getId())) {
                    return -1;
                }
                return 0;
            }
        });
        String json = "[";
//        RoomResult roomRlt;
        PlayerResult playerRlt;
        String roomjson = "";
        int count = 0;
        for (int i = 0; i < roomsInQueue.size(); i++) {
            room = roomsInQueue.get(i);
            if (room != null) {
                roomjson = "{\"rid\": \"" + room.getId() + "\",\"rname\": \"" + room.getName() + "\",\"players\":{";
                int pcount = 0;
                for (Player player : room.getChildren().values()) {
                    playerRlt = new PlayerResult(player.getId(), player.getName());
                    playerRlt.setPid(ConvertUtil.toInt(player.getUserId()));
                    playerRlt.setAvatar(player.getAvatar());
                    playerRlt.setPos(String.valueOf(player.getPos()));
                    if (pcount != 0) {
                        roomjson += ",";
                    }
                    roomjson += "\"" + playerRlt.getPos() + "\":" + gson.toJson(playerRlt);
                    pcount++;
                }
                roomjson += "}}";
                if (count != 0) {
                    json += ",";
                }
                json += roomjson;

                count++;
            }
        }
        json += "]";
        log.info("给：" + ModelUtil.getPlayer(session).getUserId() + "房间列表信息:");
        echoMessage.setContent(json);
        sessionWrite(session, echoMessage);

    }
}
